package cn.ronghuanet.gift.datasys.listener;

import cn.ronghuanet.gift.datasys.dto.CanalSynDto;
import cn.ronghuanet.gift.doc.GoodsSpuOnsaleDetailDoc;
import cn.ronghuanet.gift.repository.GoodsSpuOnsaleDetailDocRepository;
import com.alibaba.fastjson.JSONObject;
import io.netty.util.CharsetUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.stream.Collectors;

/**
 * rocketmq 消息监听，@RocketMQMessageListener中的selectorExpression为tag，默认为*
 */
@Slf4j
@Component
@RocketMQMessageListener(topic = "example",selectorExpression="*",consumerGroup = "queue_group_test")
public class GiftOnsaleOrOffSaleDataSysListener implements RocketMQListener<MessageExt> {

    @Autowired
    private GoodsSpuOnsaleDetailDocRepository repository;
    @Override
    public void onMessage(MessageExt message) {
        byte[] body = message.getBody();
        String msg = new String(body, CharsetUtil.UTF_8);
        log.info("接收到消息：{}", msg);

        CanalSynDto canalSynDto = JSONObject
                .parseObject(msg, CanalSynDto.class);


        //上架   下架
        System.out.println(canalSynDto);

        String type = canalSynDto.getType();
        List<JSONObject> data = canalSynDto.getData();
     /*   List<GoodsSpuOnsaleDetailDoc> detailDocs = new ArrayList<>();
        data.forEach(jsonObject -> {
            detailDocs.add(jsonObject.toJavaObject(GoodsSpuOnsaleDetailDoc.class));
        });*/

        List<GoodsSpuOnsaleDetailDoc> goodsSpuOnsaleDetailDocs =
                data.stream().map(jsonObject -> jsonObject.toJavaObject(GoodsSpuOnsaleDetailDoc.class
        )).collect(Collectors.toList());

        if ("DELETE".equals(type))
        {
            //下架
            goodsSpuOnsaleDetailDocs.forEach(goodsSpuOnsaleDetailDoc -> {
                repository.deleteById(goodsSpuOnsaleDetailDoc.getId());
                log.info("下架了：{}", goodsSpuOnsaleDetailDoc.getId());
            });

        }else{
            //上架
            repository.saveAll(goodsSpuOnsaleDetailDocs);
            log.info("上架了：{}", goodsSpuOnsaleDetailDocs);
        }
    }

}
